﻿using System;

namespace NetTopologySuite.Geometries.Utilities
{
	public class Matrix
	{
		private static void SwapRows(double[][] m, int i, int j)
		{
			if (i == j)
			{
				return;
			}
			for (int k = 0; k < m[0].Length; k++)
			{
				double num = m[i][k];
				m[i][k] = m[j][k];
				m[j][k] = num;
			}
		}

		private static void SwapRows(double[] m, int i, int j)
		{
			if (i == j)
			{
				return;
			}
			double num = m[i];
			m[i] = m[j];
			m[j] = num;
		}

		public static double[] Solve(double[][] a, double[] b)
		{
			int num = b.Length;
			if (a.Length != num || a[0].Length != num)
			{
				throw new ArgumentException("Matrix A is incorrectly sized");
			}
			for (int i = 0; i < num; i++)
			{
				int num2 = i;
				for (int j = i + 1; j < num; j++)
				{
					if (System.Math.Abs(a[j][i]) > System.Math.Abs(a[num2][i]))
					{
						num2 = j;
					}
				}
				if (a[num2][i] == 0.0)
				{
					return null;
				}
				Matrix.SwapRows(a, i, num2);
				Matrix.SwapRows(b, i, num2);
				for (int k = i + 1; k < num; k++)
				{
					double num3 = a[k][i] / a[i][i];
					for (int l = num - 1; l >= i; l--)
					{
						a[k][l] -= a[i][l] * num3;
					}
					b[k] -= b[i] * num3;
				}
			}
			double[] array = new double[num];
			for (int m = num - 1; m >= 0; m--)
			{
				double num4 = 0.0;
				for (int n = m + 1; n < num; n++)
				{
					num4 += a[m][n] * array[n];
				}
				array[m] = (b[m] - num4) / a[m][m];
			}
			return array;
		}
	}
}
